<template>
  <el-dialog
    v-model="dialogVisible"
    title="学员评议表"
    width="70%"
    :before-close="handleClose"
  >
    <div class="grids">
      <div>
        <div class="item">
          <span class="bold">日期：</span>
          {{ item.date }}
        </div>
        <div class="item">
          <span class="bold">课时：</span>
          {{ field_format(current, "classHour") }}
        </div>
        <div class="item">
          <span class="bold">评议日期：</span>
          {{ item.fillTime }}
        </div>
      </div>

      <div>
        <div class="item">
          <span class="bold">时段：</span>
          {{ field_format(current, "timeRange") }}
        </div>
        <div class="item">
          <span class="bold">理论课时：</span>
          {{ field_format(current, "theoreticalClassHours") }}
        </div>
      </div>

      <div>
        <div class="item">
          <span class="bold">课次：</span>
          {{ field_format(current, "classIndex") }}
        </div>
        <div class="item">
          <span class="bold"> 实训课时： </span>
          {{ field_format(current, "practicalTrainingHours") }}
        </div>
      </div>

      <div>
        <div class="item">
          <span class="bold">授课老师：</span>
          {{ info.teachingTeacher }}
        </div>
        <div class="item flex">
          <span class="bold">课程：</span>
          <span class="curriculumDesc">{{
            field_format(current, "curriculum")
          }}</span>
        </div>
      </div>
    </div>

    <el-table :data="tableParams.rows" max-height="40vh">
      <el-table-column label="状态" prop="name" width="55" fixed="left">
        <template #default="scope">
          <el-tooltip
            class="box-item"
            v-if="scope.row.userState == 0"
            effect="dark"
            :content="`停课日期 ${scope.row.suspensionClassDate}`"
            placement="top"
          >
            <div style="color: #8530f5">停课</div>
          </el-tooltip>

          <div v-else class="status-icon">
            <img src="@/assets/images/checkIcon.png" alt="" />
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50" label="序号" fixed="left" />
      <el-table-column
        label="姓名"
        prop="user_Info.baseInfo.name"
        width="80"
        fixed="left"
      />
      <el-table-column label="性别" prop="name" width="55">
        <template #default="scope">
          {{ getGenderByIdCard(scope.row.user_Info.baseInfo.identityCard) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="user_Info.baseInfo.mobile"
        label="联系方式"
        width="120"
      />
      <el-table-column label="教学态度">
        <template #default="scope">
          {{ content_format(scope.row.userId, "teachingAttitude") }}
        </template>
      </el-table-column>
      <el-table-column label="教学内容">
        <template #default="scope">
          {{ content_format(scope.row.userId, "contentCourses") }}
        </template>
      </el-table-column>
      <el-table-column label="教学方法">
        <template #default="scope">
          {{ content_format(scope.row.userId, "trainingMethods") }}
        </template>
      </el-table-column>
      <el-table-column label="教学手段">
        <template #default="scope">
          {{ content_format(scope.row.userId, "teachingDevices") }}
        </template>
      </el-table-column>
      <el-table-column label="讲解师范">
        <template #default="scope">
          {{ content_format(scope.row.userId, "explainDemo") }}
        </template>
      </el-table-column>
      <el-table-column label="巡回指导">
        <template #default="scope">
          {{ content_format(scope.row.userId, "guidanceAspect") }}
        </template>
      </el-table-column>
      <el-table-column label="课时完成情况" width="120">
        <template #default="scope">
          {{ content_format(scope.row.userId, "completionStatus") }}
        </template>
      </el-table-column>
      <el-table-column label="意见与建议" min-width="250" show-overflow-tooltip>
        <template #default="scope">
          {{ content_format(scope.row.userId, "suggestionsOpinions") }}
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-if="tableParams['total']"
      :total="tableParams['total']"
      v-model:page="formInline.pageIndex"
      v-model:limit="formInline.pageSize"
      @pagination="getStudents"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="exportWord"> 导出 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
let props = defineProps(["archiveBinding", "type"]);
const { proxy } = getCurrentInstance();
let dialogVisible = ref(false);
let info = ref({});
let item = ref({});
let numberSections = ref(0);
let archiveBindingList = [];
let current = ref(0); //下标
let tableParams = ref({});
let formInline = ref({
  pageIndex: 1,
  pageSize: 50,
  classId: "",
  keyWords: "",
});
let evaluateList = []; //评价表
let templateUrl;

function handleClose() {
  dialogVisible.value = false;
}

function content_format(userId, type) {
  if (!evaluateList.length) return;
  for (let index = 0; index < evaluateList.length; index++) {
    const element = evaluateList[index];
    if (element.userId === userId) {
      return element[type];
    }
  }
  return "";
}

async function open(row, index) {
  current.value = index;
  item.value = { ...row };
  console.log("课次详情", row);
  getClassData(row);
  queryLessonNum(row);
  getArchiveBindingList();
  getStudents();
  getEvaluate();
  getTemplateUrl();
  dialogVisible.value = true;
}

async function getStudents() {
  formInline.value["screen"] = "1";
  formInline.value.classId = item.value.classId;
  tableParams.value = await proxy.$apis.classStudent({
    type: "list",
    data: formInline.value,
  });
  console.log("学生列表", tableParams.value);
}

async function getEvaluate() {
  evaluateList = await proxy.$apis.classReport({
    type: "student-evaluate-list",
    data: { lessonScheduleId: item.value["_id"] },
  });
  console.log("评价列表", evaluateList);
}

function field_format(index, field) {
  if (!archiveBindingList.length) return;
  try {
    return archiveBindingList[index][field];
  } catch (error) {
    console.log(`${index}-${field}`, error);
  }
}

function getGenderByIdCard(idCard) {
  if (!idCard || idCard.length !== 18) {
    throw new Error("Invalid ID card number");
  }
  const sexCode = idCard.charAt(16);
  const gender = parseInt(sexCode, 10) % 2 === 0 ? "女" : "男";
  return gender;
}

//绑定教案
async function getArchiveBindingList() {
  if (props.archiveBinding.length) {
    archiveBindingList = await proxy.$apis.scheduleRelevant({
      type: "archives-curriculum-list",
      data: { archivesId: props.archiveBinding[0]._id },
    });
  }
}

//获取排期节数
async function queryLessonNum(row) {
  numberSections.value = await proxy.$apis.teachingScheduleData({
    type: "queryLessonNum",
    data: { classId: row.classId, _id: row.courseId },
  });
}

async function getClassData(row) {
  info.value = await proxy.$apis.classData({
    type: "details",
    data: { _id: row.classId },
  });
  console.log("详情", info.value);
}

async function getTemplateUrl() {
  templateUrl = await proxy.$apis.fileTemplate({
    data: { type: props.type },
    type: "downLoad",
  });
}

function downLoadTemplate() {
  window.location.href = templateUrl;
}

async function exportWord() {
  if (!templateUrl) return proxy.$utils.showToast("请先设置模板");
  let array = proxy.$utils.deepcopy(tableParams.value.rows);
  let data = [];
  array.forEach((element) => {
    let teachingAttitude = content_format(element.userId, "teachingAttitude");
    let contentCourses = content_format(element.userId, "contentCourses");
    let trainingMethods = content_format(element.userId, "trainingMethods");
    let teachingDevices = content_format(element.userId, "teachingDevices");
    let explainDemo = content_format(element.userId, "explainDemo");
    let guidanceAspect = content_format(element.userId, "guidanceAspect");
    let completionStatus = content_format(element.userId, "completionStatus");
    let suggestionsOpinions = content_format(
      element.userId,
      "suggestionsOpinions"
    );
    data.push({
      //态度
      attitude1: teachingAttitude == "好",
      attitude2: teachingAttitude == "较好",
      attitude3: teachingAttitude == "尚可",
      attitude4: teachingAttitude == "差",
      //内容
      content1: contentCourses == "好",
      content2: contentCourses == "较好",
      content3: contentCourses == "尚可",
      content4: contentCourses == "差",
      //方法
      method1: trainingMethods == "好",
      method2: trainingMethods == "较好",
      method3: trainingMethods == "尚可",
      method4: trainingMethods == "差",
      //手段
      device1: teachingDevices == "好",
      device2: teachingDevices == "较好",
      device3: teachingDevices == "尚可",
      device4: teachingDevices == "差",
      //讲解
      demo1: explainDemo == "好",
      demo2: explainDemo == "较好",
      demo3: explainDemo == "尚可",
      demo4: explainDemo == "差",
      //巡回
      guidance1: guidanceAspect == "好",
      guidance2: guidanceAspect == "较好",
      guidance3: guidanceAspect == "尚可",
      guidance4: guidanceAspect == "差",
      //课时
      hour1: completionStatus == "好",
      hour2: completionStatus == "较好",
      hour3: completionStatus == "尚可",
      hour4: completionStatus == "差",
      suggestionsOpinions,
      //评议时间
      year: proxy.$utils.dateTimeFormateFn(item.value["fillTime"], "year"),
      month: proxy.$utils.dateTimeFormateFn(item.value["fillTime"], "month"),
      day: proxy.$utils.dateTimeFormateFn(item.value["fillTime"], "day"),
      //等级
      occupationalLevel: info.value.occupationalLevel || "",
      teachingTeacher: info.value.teachingTeacher,
      className: info.value.className,
      classHours: info.value.classHours,
    });
  });
  let url = await proxy.$apis.classDocExport({
    templateURL: templateUrl,
    data: { list: data },
    fileName: "学员评议表.docx",
  });
  window.location.href = url;
}

defineExpose({ open });
</script>

<style lang="scss" scoped>
.item {
  margin-bottom: 15px;
  span {
    flex-shrink: 0;
  }
}
.status-icon {
  width: 15px;
  height: 15px;
  img {
    width: 100%;
    display: block;
  }
}
.curriculumDesc {
  overflow: hidden;
  text-overflow: ellipsis;
  width: calc(100% - 50px);
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  word-break: break-all;
}
</style>
